package com.quectel.cms.config;

import com.quectel.cms.interceptor.LoginUserSession;
import com.quectel.cms.util.MyRequestContextHolder;
import com.quectel.cms.util.SessionHolder;
import com.quectel.sys.module.sys.dto.mongo.SysLogDto;
import com.quectel.sys.module.sys.service.SysLogService;
import com.quectel.util.aspect.log.LogCallback;
import com.quectel.util.aspect.log.LogDetail;
import com.quectel.util.aspect.log.LogMethodInterceptor;
import com.quectel.util.aspect.log.LogPointCutAdvisor;
import com.quectel.util.http.RequestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * log切面配置
 *
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2023-11-28 14:19:00
 */
@Configuration
public class LogAspectConfig {
    /**
     * 定义拦截器
     *
     * @return
     */
    @Bean
    public LogMethodInterceptor logMethodInterceptor(LogHandler logHandler) {
        return new LogMethodInterceptor(logHandler);
    }

    /**
     * 定义切点,并绑定拦截器
     *
     * @param logMethodInterceptor
     * @return
     */
    @Bean
    public LogPointCutAdvisor logPointCutAdvisor(LogMethodInterceptor
                                                         logMethodInterceptor) {

        return new LogPointCutAdvisor(logMethodInterceptor);

    }

    /**
     * log处理
     */
    @Component
    public static class LogHandler implements LogCallback {
        /**
         * service
         */
        @DubboReference
        private SysLogService sysLogService;


        @Override
        public void callback(LogDetail detail) {
            LoginUserSession session = SessionHolder.getSysUser();
            SysLogDto sysLogDto = new SysLogDto();
            if (session != null) {
                sysLogDto.setTenantId(session.getTenantId());
                sysLogDto.setAccount(session.getAccount());
                sysLogDto.setUsername(session.getUsername());
                sysLogDto.setGroupName(session.getGroupCode());
            }
            HttpServletRequest currentRequest = MyRequestContextHolder.getCurrentRequest();
            sysLogDto.setRequesterIp(RequestUtils.getRealIp(currentRequest));
            sysLogDto.setRequestUri(currentRequest.getRequestURI());
            sysLogDto.setMethodString(detail.getMethod().toString());
            sysLogDto.setExecuteDuration(detail.getEndTime().getTime() - detail.getStartTime().getTime());

            sysLogDto.setLog(detail.getLog());
            sysLogDto.setCreateTime(detail.getStartTime());
            sysLogService.save(sysLogDto);
        }
    }
}
